import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, Form, message } from 'antd';
import Base from './base';
import useVariableData from 'src/hook/useVariableData';
import useActionsData from 'src/hook/useActionsData';
import useOperatorData from 'src/hook/useOperatorData';
import Modal from 'src/components/Modal';
import StrategySimpleComponent from '../Component/SimpleList';
import { cloneDeep } from 'lodash';
import services from 'src/services/api';
import StrategyConfig from '../Component/StrategyConfig';
import StrategyBaseDetail from './strategyBaseDetail';
import { USAGE_SCOPE_LIMIT, VARIABLE_TYPE } from 'src/utils/constant';
import './index.less';

/** @Method StrategyNode 节点
 *  @prop appId
 *  @prop eventId
 *  @prop codes
 *  @prop detail
 */

function StrategyNode(props) {
  console.log(props, 888);
  const { id, name, strategy_mode } = props.value || {};
  const { isLimitMode = false, disabled } = props; // 是否限制死mode,只能选择这种mode
  const [mode, setMode] = useState(strategy_mode);
  const [detail, setDetail] = useState({});
  const [strategyId, setStrategyId] = useState(id);
  const [compareData, setCompareData] = useState({});
  const variable = useVariableData({
    limitType: [
      VARIABLE_TYPE._FIELD,
      VARIABLE_TYPE._FEATURE,
      VARIABLE_TYPE._MODEL,
      VARIABLE_TYPE._NAMELIST,
      VARIABLE_TYPE._THIRD_FEATURE,
      VARIABLE_TYPE._STRATEGY,
      VARIABLE_TYPE._RISK_LEVEL,
      VARIABLE_TYPE._LITERAL,
    ],
    appId: props.appId,
    eventId: props.eventId,
    codes: props.codes,
  });
  const actions = props.isImportant ? props.actions || [] : useActionsData(USAGE_SCOPE_LIMIT._STRATEGY); //获取动作函数的列表
  const operator = useOperatorData();
  useEffect(() => {
    if (strategyId) {
      getDetailData();
    }
  }, [strategyId]);

  // 当有对比对象的时候，需要请求对比的组件内容
  useEffect(() => {
    if (props.compareData) {
      console.log(props.compareData);
      getAsyncDetail(props.compareData.id, props.compareData.version)
        .then((data) => {
          setCompareData(cloneDeep(data));
        })
        .catch((err) => {});
    }
  }, [props.compareData]);

  useEffect(() => {
    console.log(props);
    props.id && setStrategyId(props.id);
  }, [props.id]);

  // 设置detail数据
  function setDetailData(data) {
    setMode(data.mode);
    setDetail(data);
  }
  // 导入时，详情
  function getDetailData() {
    const lists = props.importData;
    if (Array.isArray(lists)) {
      const details = lists.find((item) => item.id === strategyId) || {};
      setDetailData(cloneDeep(details));
    } else {
      getDetail(strategyId);
    }
  }

  // 获取详情
  function getDetail(id, version) {
    console.log('获取详情', id);
    setStrategyId(id);
    getAsyncDetail(id, version)
      .then((data) => {
        data.config = JSON.parse(data.config);
        console.log(data, 999);
        setDetailData(cloneDeep(data));
      })
      .catch((err) => message.error(err));
  }

  // 封装一个promise的异步请求方法
  function getAsyncDetail(id, version) {
    console.log(id, version);
    return new Promise((resolve, reject) => {
      const params = version ? { id: id, versionId: version } : { id: id };
      services.strategyComponent.queryOne(params).then((res) => {
        if (res.code === '0') {
          resolve(res.data);
        } else {
          reject(res.msg);
        }
      });
    });
  }

  // 打开策略引用列表
  function openStrategyList() {
    const index = Modal.open({
      title: '引用组件',
      width: '1100px',
      content: (
        <StrategySimpleComponent
          app_id={props.appId || -1}
          event_id={props.eventId || -1}
          product_id={props.productId}
          id={strategyId}
          closeModal={() => Modal.close(index)}
          onOkHandle={(id, version) => {
            getDetail(id, version);
            Modal.close(index);
          }}
          isLimitMode={isLimitMode}
          projectCode={props.projectCode}
          strategy_mode={mode}
        />
      ),
      maskClosable: false,
      isOkBtn: false,
      isCancelBtn: false,
    });
  }

  // 提交
  function handleSubmit(e) {
    if (props.disabled) {
      props.close && props.close();
      return;
    }
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const params = {};
        if (props.value.id) {
          params.id = props.value.id;
        }
        params.label = values.name;
        params.name = values.name;
        params.id = strategyId;
        params.mode = values.mode;
        params.is_break = detail.is_break;
        if (props.sourceId) {
          params.sourceId = props.sourceId;
        }
        if (!strategyId) {
          message.warning('请引用组件');
          return;
        }
        props.onSubmit && props.onSubmit(params);
      }
    });
  }
  return (
    <div className='stretegy-wp'>
      <Form onSubmit={() => false} className='stretegy-wp-form'>
        <div className='tantuer-field-area no-padding'>
          <div className='form-title'>基本信息</div>
          <Base {...props} value={{ name, strategy_mode: mode }} />
        </div>
        <div className='tantuer-field-area no-padding'>
          <div className='flex flex-space-between'>
            <div className='form-title'>规则详情</div>
            <Button style={{ marginBottom: '16px' }} onClick={openStrategyList} disabled={disabled}>
              引用组件
            </Button>
          </div>
          {detail && Object.keys(detail).length > 0 && (
            <div className='strategy-component-detail'>
              <StrategyBaseDetail {...props} detail={detail} mode={mode} name={name} disabled={true} />
              <StrategyConfig
                {...props}
                compareData={compareData}
                mode={mode}
                variable={variable}
                using_variables={detail.using_variables}
                actions={actions}
                config={detail.config}
                appId={props.appId}
                eventId={props.eventId}
                is_exec_condition={
                  detail.config && detail.config.condition_groups && detail.config.condition_groups.length > 0
                }
                operator={operator}
                disabled={true}
                isHideTitle={true}
              />
            </div>
          )}
        </div>

        <Row type='flex' justify='start' className='form-submit-area form-submit-area2'>
          <Col>
            <Button type='primary' onClick={handleSubmit} autoFocus={true}>
              确定
            </Button>
            <Button style={{ marginLeft: '15px' }} onClick={() => props.close && props.close()}>
              取消
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Form.create()(StrategyNode));
